﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PositionalIndexer
{
    public class Indexer
    {
        public SortedDictionary<string, SortedDictionary<int, List<int>>> IndexDictionary { get; set; }

        public Indexer()
        {
            IndexDictionary = new SortedDictionary<string, SortedDictionary<int, List<int>>>();
        }

        public void GenerateIndex(Dictionary<int, Token> tokenDictionary)
        {
            foreach (Token token in tokenDictionary.Values)
            {
                if (IndexDictionary.ContainsKey(token.Name))
                {
                    if (IndexDictionary[token.Name].ContainsKey(token.DocID))
                    {
                        IndexDictionary[token.Name][token.DocID].Add(token.Position);
                    }
                    else
                    {
                        List<int> posList =  new List<int>();
                        posList.Add(token.Position);
                        IndexDictionary[token.Name].Add(token.DocID, posList);
                    }

                }
                else
                {
                    SortedDictionary<int, List<int>> dic = new SortedDictionary<int, List<int>>();
                    List<int> posList =  new List<int>();
                    posList.Add(token.Position);
                    dic.Add(token.DocID, posList);
                    IndexDictionary.Add(token.Name, dic);
                }
            }
        }

        public StringBuilder FormatIndex(Indexer indexer)
        {
            StringBuilder text = new StringBuilder();
            string docID = "";
            string position = "";
            foreach (KeyValuePair<string, SortedDictionary<int, List<int>>> index in indexer.IndexDictionary)
            {
                foreach (KeyValuePair<int, List<int>> doc in index.Value)
                {
                    foreach (int pos in doc.Value)
                    {
                        if (position == "")
                        {
                            position += pos;
                        }
                        else
                        {
                            position += ", " + pos;
                        }
                    }
                    docID += doc.Key + ", " + doc.Value.Count + ": <" + position + ">;\n  ";
                    position = "";
                }
                text.AppendFormat("{0}, " + index.Value.Count + ":\n<{1}>\n", index.Key, docID);
                docID = "";
            }
            return text;
        }
    }
}
